package com.fansl.allround.study.Interview;

/**
 * @author fansl
 * @Description: 链表
 * @date 2019/10/24 15:14
 */
public class LinkList {
    class Node{
        private Object data;
        private Node next;
        public Node(Object data){
            this.data = data;
            this.next = null;
        }
    }
    private Node head;

    public LinkList(){
        //初始化头部
        this.head = new Node(null);
    }

    /**
     * 根据value查找节点
     * @param value
     * @return
     */
    public Node findByValue(Object value){
        Node currentNode = this.head;
        while(currentNode !=null && ! currentNode.data.equals(value)){
            currentNode = currentNode.next;
        }
        return currentNode==null?null:currentNode;
    }

    public Node findByIndex(int index){
        int pos = 0;
        Node currentNode = this.head;
        while (currentNode!=null&&pos!=index){
            currentNode = currentNode.next;
            pos++;
        }
        return currentNode==null?null: currentNode;
    }

    public void add(Object data){
        Node currentNode = this.head;
        if(currentNode.data==null){
            currentNode.data = data;
            return;
        }
        Node proNode = currentNode;
        while(currentNode !=null && currentNode.data!=null){
            proNode = currentNode;
            currentNode = currentNode.next;
        }
        Node newNode = new Node(data);
        proNode.next = newNode;
    }

    public void add(int index,Object data){
        Node currentNode = this.findByIndex(index);
        if(currentNode==null){
            System.out.println("未找到指定位置："+index);
            return;
        }
        Node newNode = new Node(data);
        newNode.next= currentNode.next;
        currentNode.next = newNode;
    }

    public void delete(int index){
        Node preNode = null;
        Node currentNode = this.findByIndex(index);
        if(currentNode==null){
            System.out.println("未找到指定位置："+index);
            return;
        }
        preNode.next=currentNode.next;
    }

    public void print(){
        Node currentNode = this.head;
        while (currentNode!=null){
            System.out.println(currentNode.data);
            currentNode= currentNode.next;
        }
    }

    public static void main(String[] args) {
        LinkList linkList = new LinkList();
        linkList.add("1");
        linkList.add("2");
        linkList.add("3");
        linkList.print();
    }
}
